package jp.gr.jted;

import java.net.URL;
import java.util.ArrayList;

import jp.gr.jted.bean.AppBean;
import jp.gr.jted.bean.Talk;
import jp.gr.jted.util.TedUtil;
import jp.gr.jted.util.Util;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class JTEDActivity extends ListActivity implements Runnable{

	private int pageNum = 0;
	private ArrayList<Talk> list = null;
	private TalkAdapter adapter = null;
	private TedUtil tedUtil = null;
	private AppBean appBean = null;
	private Handler handler = null;
	private Talk asyncTalk;
	private boolean readFlag = true;
	private ListView listView;
//	private LinearLayout footer;

	/** Called when the activity is first created. */
	@SuppressWarnings("rawtypes")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// hide the title
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		this.appBean = (AppBean) this.getApplication();
		this.tedUtil = new TedUtil();
		this.list = new ArrayList<Talk>();
		adapter = new TalkAdapter(this, R.layout.talk_row, new ArrayList());
		handler = new Handler();
		
//		footer = (LinearLayout) getLayoutInflater().inflate(R.layout.talk_footer,null);
		listView = getListView();
		listView.setAdapter(adapter);
		listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if(list.size() != 0){
					if ((firstVisibleItem + visibleItemCount) == list.size()) {
//						listView.addFooterView(footer);
						showTalkList();
						return;
					}
				}
			}

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				
			}
		});
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				Talk talk = list.get(position);
				appBean.setTalk(talk);
				Log.d(Definition.TAG,talk.getTitle());
				Intent intent = new Intent(JTEDActivity.this,MultiViewActivity.class);
				intent.setAction(Intent.ACTION_VIEW);
				startActivity(intent);
			}
		});

		try{
			// 初回起動時のダイアログ表示	
			Log.d(Definition.TAG,"check first launch.");
			if(Util.isFirstLaunch(this)){
				Util.writeVersionToDevice(this);
				showDialog(Definition.FIRST_DIALOG);
			}else{
				checkNetwork();
			}

		}catch(Exception e){
			Log.e(Definition.TAG,e.getMessage());
		}
	}

	public void checkNetwork(){
		// ネットワークチェック
		Log.d(Definition.TAG,"check network state");
		if(!Util.canNetworkCommunication(this)){
			showDialog(Definition.NETWORK_ERROR);
		}else{
			showTalkList();
		}
	}

	public void showTalkList(){
		if(readFlag){
			this.pageNum++;
			readFlag = false;
			Thread thread = new Thread(this);
			thread.start();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Log.v(Definition.TAG, String.format("onCreateDialog id=%d", id));
		Dialog dialog = null;
		ViewGroup root;
		View layout;
		switch(id) {
		case Definition.FIRST_DIALOG:
			Log.d(Definition.TAG, "RootActivity#onCreateDialog<FIRST_SCR>");
			root = (ViewGroup) findViewById(R.id.first_launch_dialog);
			layout = getLayoutInflater().inflate(R.layout.first_launch_dialog, root);
			dialog = new AlertDialog.Builder(this)
			.setTitle(R.string.first_dialog_title)
			.setCancelable(false)
			.setView(layout)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					checkNetwork();
				}
			}).create();
			break;
		case Definition.NETWORK_ERROR:
			Log.d(Definition.TAG, "RootActivity#onCreateDialog<NETWORK_ERROR>");
			root = (ViewGroup) findViewById(R.id.message_dialog);
			layout = getLayoutInflater().inflate(R.layout.message_dialog, root);
			TextView message = (TextView) layout.findViewById(R.id.message);
			message.setText(R.string.network_error);
			dialog = new AlertDialog.Builder(this)
			.setTitle(R.string.warning)
			.setCancelable(false)
			.setView(layout)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					showTalkList();
				}
			}).create();
			break;
		}
		return dialog;
	}

	@Override
	public void run() {
		try{
//			Log.d(Definition.TAG,"page : " + pageNum);
			ArrayList<Talk> talkList = tedUtil.getTalkList(pageNum);
			for(Talk talk : talkList){
//				Log.d(Definition.TAG,talk.getTitle());
				list.add(talk);
				try {
					URL url = new URL(talk.getThumbnail());
					Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
					talk.setBitmap(bitmap);
				} catch (Exception e) {
					Log.d(Definition.TAG,e.getMessage());
				}
				this.asyncTalk = talk;
				synchronized(asyncTalk){
					handler.post(new Runnable(){
						@Override
						public void run() {
								adapter.add(asyncTalk);
							}
					});
				}
			}
			readFlag = true;
		}catch(Exception e){
			Log.d(Definition.TAG,e.getMessage());
		}
	}
}